package com.glsc.ngateway.flowable.service;

import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableAppendDto;
import com.glsc.ngateway.common.base.converter.flowable.FlowableAppendConverter;
import com.glsc.ngateway.flowable.constant.FlowableConstant;
import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableAppend;
import com.glsc.ngateway.common.base.domain.mysql.gateway.oaflow.TOaFlowAppendTable;
import com.glsc.ngateway.common.base.repo.mysql.flowable.FlowableAppendRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.oaflow.TOaFlowAppendTableRepository;
import com.glsc.ngateway.flowable.util.DateUtil;
import com.glsc.ngateway.flowable.util.DocUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class FlowableAppendService {

    Logger logger = LoggerFactory.getLogger(FlowableAppendService.class);

    @Autowired
    FlowableAppendRepo appendRepo;
    @Autowired
    FlowableConstant flowableConstant;

    @Autowired
    TOaFlowAppendTableRepository tOaFlowAppendTableRepository;

    //对应controller uploadDoc方法
    public String updateAppendix(String fileName, String filePath, MultipartFile file) throws IOException {
        String appendixId = UUID.randomUUID().toString();

        //通过flowable上传附件用20220101格式
        //通过oaflow上传附件用2022-01-01格式  要注意 已经统一成20220101格式
        String today = DateUtil.today();
        String resPath = DocUtils.saveFile(file.getBytes(), filePath + today + "/" + appendixId + "/", fileName);
        if (null == fileName || fileName.equals("")) {
            throw new RuntimeException("上传文件异常，文件名称为空");
        }
        if (resPath.equals("Exception")) {
            throw new RuntimeException("上传文件异常，文件名称为：" + fileName);
        }
        appendRepo.save(FlowableAppend.builder().appendixName(fileName).appendixPath(resPath).appendixId(appendixId).build());
        tOaFlowAppendTableRepository.save(new TOaFlowAppendTable(fileName, resPath, appendixId));
        return flowableConstant.DOC_WEB_URL + appendixId;
    }

    //对应controller oaDownloadAppendix方法
    public String getAppendixPathById(String appendixId) {
        return appendRepo.getAppendixPathById(appendixId);
    }


    public List<FlowableAppendDto> findByAppendixIdIn(List<String> appendixIds) {
        return FlowableAppendConverter.domain2Dto(appendRepo.findByAppendixIdIn(appendixIds));
    }
}
